package com.order.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.order.common.CommonResult;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        CommonResult result = CommonResult.fail("未知异常");
        if (e instanceof FlowException) {
            result.setMsg("请求被限流了");
        } else if (e instanceof ParamFlowException) {
            result.setMsg("请求被热点参数限流");
        } else if (e instanceof DegradeException) {
            result.setMsg("请求被降级了");
        } else if (e instanceof AuthorityException) {
            result.setMsg("没有权限访问");
            result.setStatus(401);
        }
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(result.getStatus());
        response.getWriter().println(JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue));
    }
}
